<template>
  <el-form
    ref="formRef"
    :model="model"
    :rules="rules"
    label-width="100px"
    label-position="left"
  >
    <el-form-item
      v-if="!isEdit"
      label="围栏名称"
      prop="title"
      required
    >
      <el-input
        v-model="model.title"
        placeholder="请输入围栏名称"
      />
    </el-form-item>

    <el-form-item
      v-if="fenceType === FenceType.CIRCLE && !isEdit"
      label="围栏半径"
      required
      prop="circular_radius"
    >
      <div class="flex">
        <el-input-number
          v-model="model.circular_radius"
          :min="100"
          :step="50"
          :disabled="isEdit"
          label="请输入围栏半径"
          @change="handleRadiusChange"
        />
        <div class="radius-tips">
          <span>米</span>
          <span> / {{ circularRadiusFormatter }}</span>
        </div>
      </div>
    </el-form-item>

    <el-form-item
      v-if="fenceType === FenceType.ADMINISTRATIVE_REGION"
      label="行政区域"
      required
      prop="adm_area_code"
    >
      <el-cascader
        ref="cascader"
        v-model="model.adm_area_code"
        :props="cascaderProps"
        placeholder="请选择行政区域"
        @change="handleCascaderChange"
      />
    </el-form-item>

    <el-form-item
      label="关联车辆"
      required
      prop="imei_list"
    >
      <el-select
        v-model="model.imei_list"
        multiple
        collapse-tags
        placeholder="请选择关联车辆"
      >
        <el-option
          v-for="item in selectorOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
    </el-form-item>

    <el-form-item
      label="进出围栏设置"
    >
      <el-checkbox
        v-model="model.in_rail_alarm"
        :true-label="1"
        :false-label="0"
      >
        进围栏报警
      </el-checkbox>

      <el-checkbox
        v-model="model.out_rail_alarm"
        :true-label="1"
        :false-label="0"
      >
        出围栏报警
      </el-checkbox>
    </el-form-item>
  </el-form>
</template>

<script>
import { FenceType } from '@/views/vehicleService/components/fenceCreate/index'
import { debounce } from 'lodash'
import { getAddress } from '@/api/basic'
import AddressSelector from '@/views/personnel-files/components/ValueWithInput/withAddress.vue'
import { value as get } from '@/utils/kris_utils'

export default {
  name: 'FenceCreateForm',
  components: { AddressSelector },
  props: {
    model: {
      type: Object,
      default: () => ({})
    },

    fenceType: {
      type: Number,
      default: 1
    },

    selectorOptions: {
      type: Array,
      default: () => []
    },

    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      rules: {
        title: [
          { required: true, message: '请输入围栏名称', trigger: ['blur', 'change'] }
        ],
        circular_radius: [
          { required: true, message: '请输入圆形围栏半径', trigger: ['blur', 'change'] }
        ],
        adm_area_code: [
          { required: true, message: '请选择行政区域', trigger: ['blur', 'change'] }
        ],
        imei_list: [
          { required: true, message: '请选择关联车辆', trigger: ['blur', 'change'] }
        ]
      },
      cascaderProps: {
        lazy: true,
        lazyLoad: async(node, resolve) => {
          try {
            console.log('node --------->', node)
            const { level } = node

            const result = await this.getAddress(level === 0 ? '' : node.data.id)

            resolve(result.data.map(item => {
              return {
                label: item.name,
                id: item.id,
                value: item.code,
                leaf: item.level >= 3
              }
            }))
          } catch (error) {
            this.$message.error(error.message)
          }
        }
      }
    }
  },
  computed: {
    FenceType() {
      return FenceType
    },
    circularRadiusFormatter() {
      const kiloMeters = this.model.circular_radius / 1000
      return `${kiloMeters.toFixed(2)} 公里`
    }
  },
  created() {

  },
  methods: {
    resetFields() {
      this.$refs.formRef.resetFields()
    },

    validate() {
      return new Promise(resolve => {
        this.$refs.formRef.validate(flag => {
          resolve(flag)
        })
      })
    },

    handleRadiusChange: debounce(function(e) {
      this.$emit('radiusChange', e)
    }, 500),

    async getAddress(id) {
      const result = await getAddress(id)
        .catch(err => {
          throw new Error('获取地址失败')
        })

      if (result.code !== 200 || !Array.isArray(result.data)) { throw new Error('获取地址失败') }

      return result
    },

    find(options, path, valueKey = 'value', childrenKey = 'children') {
      if (!Array.isArray(options) || !Array.isArray(path)) { return [] }

      const holder = {
        options,
        path: []
      }

      return path.reduce((prev, current, index) => {
        const target = prev.options.find(item => item[valueKey] === current)

        if (target === null) { return [] }

        prev.options = target[childrenKey]
        prev.path.push(target)

        return index >= (path.length - 1) ? prev.path : prev
      }, holder)
    },

    pathWithLabel(value) {
      const options = get(this.$refs, 'cascader.$refs.panel.store.nodes')
      if (!Array.isArray(value) || !Array.isArray(options)) { return [] }

      return this
        .find(options, value)
        .map(item => ({ label: item.label, value: item.value }))
    },

    handleCascaderChange(e) {
      console.log('e --------->', e)
      console.log('model.adm_area_code --------->', this.model.adm_area_code)
    }
  }
}
</script>
<style lang="scss" scoped>
.radius-tips {
  margin-left: 10px;
  padding: 0 10px;
  border-radius: 5px;
  background-color: #F5F5F5;
}
</style>
